

import logging
from trytond.transaction import Transaction
from trytond.model import ModelView, ModelSQL, ModelSingleton, fields
from trytond.wizard import Wizard, StateView, Button, StateTransition
from trytond.pyson import Eval
from tools import create_sequence, create_config
from trytond.pool import Pool, PoolMeta

__all__ = ['Company','CompanyWizard', 'CompanyCreateStart']
__metaclass__ = PoolMeta

class Company:
    __name__ = 'company.company'

    ultimo_z = fields.Integer('Ultimo Z procesado')


class CompanyWizard(Wizard):
    "Creates a Company"
    __name__ = "oris.company.create"

    start = StateView('company.company',
        'company.company_view_form', [
            Button('Cancel', 'end', 'tryton-cancel'),
            Button('Next', 'company', 'tryton-ok', True), # Go to company StateView (next step)
            ])

    company = StateView('oris.company.create.start',
        'oris.company_creation_start_view_form', [
            Button('Cancel', 'end', 'tryton-cancel', default=True),
            Button('Create', 'create_', 'tryton-ok'),  # Go to create_
            ])

    create_ = StateTransition()

    def transition_create_(self):
        logger = logging.getLogger('Company')

        pool = Pool()
        user_obj = pool.get('res.user')
        group_obj = pool.get('res.group')

        logger.info("Creating a new Company '" + self.start.party.name + "' ...")
        self.start.save()
        logger.info('Company created with id: ' + str(self.start.id))

        logger.info("Creating user administrator...")

        # Searching all groups
        grps = group_obj.search([('id','>',-1)])

        user_id = user_obj()
        user_id.name = self.start.party.name + ' Admin'
        user_id.login = self.company.admin_user
        user_id.password = self.company.admin_user
        user_id.company = self.start
        user_id.main_company = self.start
        user_id.groups = grps
        user_id.save()

        logger.info(' Current user: ' + str(Transaction().user) + ' - New user: ' + str(user_id.id))

        with Transaction().set_user(user_id.id) :
            logger.info(' Changing to user: ' + str(Transaction().user))

            comp = Transaction().context.get('company')
            Transaction().context['company'] = self.start.id 

            logger.info("     Inventory sequence...")
            create_config('pcw.stock.configuration', 'inventory_sequence', 
                            create_sequence( 'Inventory', 'pcw.stock.inventory', 'INV-' + self.company.prefix + '-', self.start, False))
            logger.info("     Production sequence...")
            create_config('pcw.production.configuration', 'production_sequence', 
                            create_sequence( 'Inventory', 'pcw.production.order', 'PRD-' + self.company.prefix + '-', self.start, False))
            logger.info("     Sale sequence...")
            create_config('pcw.sale.configuration', 'sale_sequence', 
                            create_sequence( 'Sale', 'pcw.sale', 'VTA-' + self.company.prefix + '-', self.start, False))
            logger.info("     Purchase sequence...")
            create_config('pcw.purchase.configuration', 'purchase_sequence', 
                            create_sequence( 'Purchase', 'pcw.purchase', 'COM-' + self.company.prefix + '-', self.start, False))
            logger.info("     Waste sequence...")
            create_config('pcw.waste.configuration', 'waste_sequence', 
                            create_sequence( 'Waste', 'pcw.waste', 'WAS-' + self.company.prefix + '-', self.start, False))

            Transaction().context['company'] = comp

        logger.info('Company created with id: ' + str(self.start.id))
        return 'end'

class CompanyCreateStart(ModelView):
    "Creates a Company"
    __name__ = 'oris.company.create.start'

    # Aqui van los campos con la informacion que queremos para crear la empresa

    admin_user = fields.Char('Usuario administrador', required=True)
    prefix = fields.Char('Sequence Prefix', size=2)

